#include <iostream>
#include <fstream>

#include <numeric>   // accumulate
#include <algorithm> // max_element, min_element

using namespace std;

float FindAve(float a[], int len);

void HighLow(float high[], float low[], int len, float* pHigh, float* pLow);

#define FILE_IN "ch06/weather.in"
#define FILE_OUT "report.out"

int main() {
    // 读取数据
    ifstream input;
    input.open(FILE_IN, ios::in);
    if (!input) {
        cout << "未找到输入文件 " << FILE_IN << "\n";
        cout << "退出程序, 再见\n";
        exit(1);
    }
    cout << "文件找到，继续执行...\n";

    char date[25];
    char location[50];

    input.getline(date, 24);
    input.getline(location, 49);

    float high[31];
    float low[31];
    int total_days = 0;
    for (; !input.eof(); total_days++) {
        input >> high[total_days] >> low[total_days];
    }

    input.close();
    cout << "数据读取完毕\n";

    // 分析数据
    float high_ave = FindAve(high, total_days);
    float low_ave = FindAve(low, total_days);

    float hottest;
    float coldest;
    HighLow(high, low, total_days, &hottest, &coldest);

    // 生成报告
    ofstream output;
    output.open(FILE_OUT, ios::out);
    output << "Monthly Weather Report\n"
        << "Location: " << location << "\n"
        << "Date: " << date << "\n"
        << "Average Temperatures High: " << high_ave
        << ", Low: " << low_ave << "\n"
        << "Hottest Temperature: " << hottest << "\n"
        << "Coldest Temperature: " << coldest << "\n";
    output.close();
}

float FindAve(float a[], int len) {
    return accumulate(a, a+len, 0.0f) / len;
}

void HighLow(float high[], float low[], int len, float* pHigh, float* pLow) {
    *pHigh = *max_element(high, high+len);
    *pLow = *min_element(low, low+len);
}

